<?php
namespace app\common\service;

use think\Db;

/**
 * 用户权限服务类
 */
class UserPermissionService
{
    /**
     * 根据用户ID和角色权限获取符合条件的用户ID数组
     * @param int $userId 用户ID
     * @return array 符合条件的用户ID数组
     */
    public static function getUsersByPermission($userId)
    {
        // 1. 获取用户信息
        $user = Db::name('user')->where('id', $userId)->find();
        if (!$user) {
            return [];
        }
        
        // 2. 获取用户角色权限类型
        $role = Db::name('role')->where('id', $user['role_id'])->find();
        if (!$role) {
            return [];
        }
        
        $dataPermissionType = $role['dataPermissionType'];
        // 3. 根据权限类型获取用户列表
        switch ($dataPermissionType) {
            case 1: // 本人
                return [$userId];
                
            case 2: // 本人及下属
                return self::getSelfAndSubordinates($userId);
                
            case 3: // 本部门
                return self::getDepartmentUsers($user['department_id']);
                
            case 4: // 仅下属部门
                return self::getSubordinateDepartmentsUsers($user['department_id']);
                
            case 5: // 本部门及下属部门
                return self::getDepartmentAndSubordinateUsers($user['department_id']);
                
            case 6: // 全部
                return self::getAllUsers();
                
            default:
                return [$userId];
        }
    }
    
    /**
     * 获取本人及下属用户ID
     * @param int $userId 用户ID
     * @return array 用户ID数组
     */
    private static function getSelfAndSubordinates($userId)
    {
        $userIds = [$userId];
        
        // 递归获取所有下属
        $subordinates = self::getSubordinatesRecursive($userId);
        $userIds = array_merge($userIds, $subordinates);
        
        return array_unique($userIds);
    }
    
    /**
     * 获取本部门用户ID
     * @param int $departmentId 部门ID
     * @return array 用户ID数组
     */
    private static function getDepartmentUsers($departmentId)
    {
        if (!$departmentId) {
            return [];
        }
        
        return Db::name('user')
            ->where('department_id', $departmentId)
            ->where('is_delete', 0)
            ->column('id');
    }
    
    /**
     * 获取下属部门用户ID
     * @param int $departmentId 部门ID
     * @return array 用户ID数组
     */
    private static function getSubordinateDepartmentsUsers($departmentId)
    {
        if (!$departmentId) {
            return [];
        }
        
        $userIds = [];
        
        // 获取本部门中作为leader的用户ID
        $leaderUserIds = Db::name('user')
            ->where('department_id', $departmentId)
            ->where('is_delete', 0)
            ->whereNotNull('leader_id')
            ->column('id');
        
        // 获取这些leader的下属用户
        foreach ($leaderUserIds as $leaderId) {
            $subordinateUserIds = self::getSubordinatesRecursive($leaderId);
            $userIds = array_merge($userIds, $subordinateUserIds);
        }
        
        return array_unique($userIds);
    }
    
    /**
     * 递归获取下属用户ID
     * @param int $leaderId 上级用户ID
     * @return array 下属用户ID数组
     */
    private static function getSubordinatesRecursive($leaderId)
    {
        $userIds = [];
        
        // 获取直接下属
        $subordinates = Db::name('user')
            ->where('leader_id', $leaderId)
            ->where('is_delete', 0)
            ->column('id');
        
        $userIds = array_merge($userIds, $subordinates);
        
        // 递归获取下属的下属
        foreach ($subordinates as $subId) {
            $subUserIds = self::getSubordinatesRecursive($subId);
            $userIds = array_merge($userIds, $subUserIds);
        }
        
        return $userIds;
    }
    
    /**
     * 获取本部门及下属部门用户ID
     * @param int $departmentId 部门ID
     * @return array 用户ID数组
     */
    private static function getDepartmentAndSubordinateUsers($departmentId)
    {
        if (!$departmentId) {
            return [];
        }
        
        $userIds = [];
        
        // 本部门用户
        $deptUserIds = self::getDepartmentUsers($departmentId);
        $userIds = array_merge($userIds, $deptUserIds);
        
        // 下属部门用户（基于leader_id的下属人员所在部门）
        $subDeptUserIds = self::getSubordinateDepartmentsUsers($departmentId);
        $userIds = array_merge($userIds, $subDeptUserIds);
        
        return array_unique($userIds);
    }
    
    /**
     * 获取全部用户ID
     * @return array 用户ID数组
     */
    private static function getAllUsers()
    {
        return Db::name('user')
            ->where('is_delete', 0)
            ->column('id');
    }
    
    /**
     * 检查用户是否有权限操作指定用户
     * @param int $currentUserId 当前用户ID
     * @param int $targetUserId 目标用户ID
     * @return bool 是否有权限
     */
    public static function hasPermission($currentUserId, $targetUserId)
    {
        $permittedUserIds = self::getUsersByPermission($currentUserId);
        return in_array($targetUserId, $permittedUserIds);
    }
    
    /**
     * 获取用户权限范围内的用户列表（包含详细信息）
     * @param int $userId 用户ID
     * @return array 用户信息数组
     */
    public static function getUsersWithInfo($userId)
    {
        $userIds = self::getUsersByPermission($userId);
        
        if (empty($userIds)) {
            return [];
        }
        
        return Db::name('user')
            ->where('id', 'in', $userIds)
            ->where('is_delete', 0)
            ->field('id, name, username, department_id, leader_id')
            ->select();
    }
    
    /**
     * 获取用户权限范围内的部门列表
     * @param int $userId 用户ID
     * @return array 部门信息数组
     */
    public static function getDepartmentsByPermission($userId)
    {
        $user = Db::name('user')->where('id', $userId)->find();
        if (!$user) {
            return [];
        }
        
        $role = Db::name('role')->where('id', $user['role_id'])->find();
        if (!$role) {
            return [];
        }
        
        $dataPermissionType = $role['dataPermissionType'];
        
        switch ($dataPermissionType) {
            case 1: // 本人
                return [];
                
            case 2: // 本人及下属
                return self::getUserDepartments($userId);
                
            case 3: // 本部门
                return self::getDepartmentInfo($user['department_id']);
                
            case 4: // 仅下属部门
                return self::getSubordinateDepartmentsInfo($user['department_id']);
                
            case 5: // 本部门及下属部门
                return self::getDepartmentAndSubordinateInfo($user['department_id']);
                
            case 6: // 全部
                return self::getAllDepartments();
                
            default:
                return [];
        }
    }
    
    /**
     * 获取用户所在部门信息
     * @param int $userId 用户ID
     * @return array 部门信息数组
     */
    private static function getUserDepartments($userId)
    {
        $user = Db::name('user')->where('id', $userId)->find();
        if (!$user || !$user['department_id']) {
            return [];
        }
        
        return self::getDepartmentInfo($user['department_id']);
    }
    
    /**
     * 获取部门信息
     * @param int $departmentId 部门ID
     * @return array 部门信息数组
     */
    private static function getDepartmentInfo($departmentId)
    {
        if (!$departmentId) {
            return [];
        }
        
        return Db::name('department')
            ->where('id', $departmentId)
            ->where('is_delete', 0)
            ->select();
    }
    
    /**
     * 获取下属部门信息
     * @param int $departmentId 部门ID
     * @return array 部门信息数组
     */
    private static function getSubordinateDepartmentsInfo($departmentId)
    {
        if (!$departmentId) {
            return [];
        }
        
        // 获取本部门中作为leader的用户ID
        $leaderUserIds = Db::name('user')
            ->where('department_id', $departmentId)
            ->where('is_delete', 0)
            ->whereNotNull('leader_id')
            ->column('id');
        
        // 获取这些leader的下属用户所在的部门ID
        $subordinateDepartmentIds = [];
        foreach ($leaderUserIds as $leaderId) {
            $subordinateUserIds = self::getSubordinatesRecursive($leaderId);
            if (!empty($subordinateUserIds)) {
                $deptIds = Db::name('user')
                    ->where('id', 'in', $subordinateUserIds)
                    ->where('is_delete', 0)
                    ->whereNotNull('department_id')
                    ->column('department_id');
                $subordinateDepartmentIds = array_merge($subordinateDepartmentIds, $deptIds);
            }
        }
        
        $subordinateDepartmentIds = array_unique($subordinateDepartmentIds);
        
        if (empty($subordinateDepartmentIds)) {
            return [];
        }
        
        return Db::name('department')
            ->where('id', 'in', $subordinateDepartmentIds)
            ->where('is_delete', 0)
            ->select();
    }
    
    /**
     * 获取本部门及下属部门信息
     * @param int $departmentId 部门ID
     * @return array 部门信息数组
     */
    private static function getDepartmentAndSubordinateInfo($departmentId)
    {
        if (!$departmentId) {
            return [];
        }
        
        $departments = [];
        
        // 本部门
        $deptInfo = self::getDepartmentInfo($departmentId);
        $departments = array_merge($departments, $deptInfo);
        
        // 下属部门（基于leader_id的下属人员所在部门）
        $subDeptInfo = self::getSubordinateDepartmentsInfo($departmentId);
        $departments = array_merge($departments, $subDeptInfo);
        
        return $departments;
    }
    
    /**
     * 获取所有部门信息
     * @return array 部门信息数组
     */
    private static function getAllDepartments()
    {
        return Db::name('department')
            ->where('is_delete', 0)
            ->select();
    }
}